<template>
  <view class="order-management">
    <!-- 顶部标题 -->
    <view class="page-header">
      <view class="search-box">
        <input
          type="text"
          placeholder="搜索订单号"
          v-model="query.searchQuery"
          @change="handleSearch()"
        />
        <icon class="search-icon" type="search" size="14"></icon>
      </view>
    </view>

    <!-- 订单状态标签页 -->
    <view class="order-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.name"
        class="tab"
        :class="{ active: currentTab === tab.name }"
        @click="currentTab = tab.name"
      >
        <view class="tab-inner">
          {{ tab.label }}
          <!-- <view v-if="getCountByStatus(tab.name) > 0" class="badge">{{
            getCountByStatus(tab.name)
          }}</view> -->
        </view>
      </view>
    </view>

    <!-- 日期筛选区域 -->
    <view class="filter-section">
      <view class="date-filter">
        <view class="filter-label">时间范围：</view>
        <input
          type="text"
          placeholder="开始日期"
          v-model="query.startDate"
          readonly
          @click="showDatePicker()"
          class="date-input"
        />
        <view class="filter-label">至</view>
        <input
          type="text"
          placeholder="结束日期"
          v-model="query.endDate"
          readonly
          @click="showDatePicker()"
          class="date-input"
        />
      </view>
      <button class="filter-btn" @click="applyFilters">筛选</button>
    </view>

    <!-- 加载中提示 -->
    <view v-if="initialLoading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">数据加载中...</text>
    </view>

    <!-- 订单列表 -->
    <view v-else-if="orders.length > 0" class="order-list">
      <view
        v-for="order in orders"
        :key="order.id"
        class="order-item"
        @click="navigateToDetail(order.order_id)"
      >
        <view class="order-header">
          <view class="header-left">
            <view class="order-no">订单号: {{ order.order_no }}</view>
            <view class="order-source" :class="'source-' + order.order_source">订单种类：{{ getOrderSource(order.order_source) }}</view>
          </view>
          <view class="order-status" :class="'status-' + currentTab">
            {{ order.state_text }}
          </view>
        </view>

        <view class="order-products">
          <view
            v-for="product in order.product"
            :key="product.id"
            class="product-item"
          >
            <image :src="product.image.file_path" class="product-image"></image>
            <view class="product-info">
              <view class="product-name">{{ product.product_name }}</view>
              <view class="product-spec">{{ product.product_attr }}</view>
              <view class="product-price-qty">
                <text class="product-price" v-if="order.order_source==10"
                  >¥{{ product.grade_product_price }}</text
                >
				<text class="product-price" v-else-if="order.order_source==20"
				  >功德分：{{ product.points_num }}</text
				>
                <text class="product-qty">x{{ product.total_num }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="order-footer">
          <view class="order-time">下单时间：{{ order.create_time }}</view>
          <view class="order-amount">
            共{{ getTotalQuantity(order.product) }}件商品
            <text class="amount-total" v-if="order.order_source==10">合计：¥{{ order.total_price }}</text>
			<text class="amount-total" v-else-if="order.order_source==20">合计：功德分:{{ order.points_num }}</text>
          </view>

          <view class="order-actions">
            <view
              v-if="
                order.order_status.value === 10 && order.pay_status.value === 10
              "
              class="action-btn primary-btn"
              @click.stop="goPay(order.order_id)"
            >
              去支付
            </view>
            <view
              v-if="
                order.order_status.value === 10 && order.pay_status.value === 10
              "
              class="action-btn cancel-btn"
              @click.stop="cancelOrder(order.order_id)"
            >
              取消订单
            </view>
            <view
              v-if="
                order.order_status.value === 10 &&
                order.delivery_status.value === 20
              "
              class="action-btn primary-btn"
              @click.stop="confirmReceived(order.order_id)"
            >
              确认收货
            </view>
            <view
              v-if="order.order_status.value === 20"
              class="action-btn primary-btn"
              @click.stop="rebuyOrder(order)"
            >
              重新购买
            </view>
            <!-- <view
              v-if="order.order_status.value === 30 && order.is_comment == 0"
              class="action-btn review-btn"
              @click.stop="writeReview(order.order_id)"
            >
              评价
            </view> -->
            <view
              class="action-btn detail-btn"
              @click.stop="navigateToDetail(order.order_id)"
            >
              查看详情
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <image src="/static/images/empty-order.png" class="empty-image"></image>
      <view class="empty-text">暂无订单</view>
      <button class="shop-now-btn" @click="navigateToShop">去购物</button>
    </view>

    <!-- 加载更多 -->
    <view
      v-if="hasMore && orders.length > 0"
      class="load-more"
      @click="loadMore"
    >
      <text v-if="!loading">加载更多</text>
      <view v-else class="loading-spinner">
        <image src="/static/images/loading.gif" class="loading-image"></image>
        <text>加载中...</text>
      </view>
    </view>
    <uni-calendar
      ref="calendar"
      class="uni-calendar--hook"
      :clear-date="true"
      :insert="false"
      :startDate="query.startDate"
      :endDate="query.endDate"
      range
      @confirm="confirmDate"
    />
  </view>
</template>

<script>
import {
	addCartApi,
  cancelOrderApi,
  cconfirmOrderApi,
  orderListApi,
} from "../../api/order";
import uniCalendar from "../../uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue";
export default {
  components: { uniCalendar },
  data() {
    return {
      tabs: [
        { name: "all", label: "全部" },
        { name: "payment", label: "待支付" },
        { name: "delivery", label: "待发货" },
        { name: "received", label: "待收货" },
        { name: "comment", label: "已完成" },
        { name: "cancelled", label: "已取消" },
      ],
      currentTab: "all",
      orders: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      initialLoading: true,
      query: {
        searchQuery: "",
        startDate: "",
        endDate: "",
      },
    };
  },
  onLoad() {
    this.init();
  },
  watch: {
    query: {
      handler() {
        this.init();
      },
      deep: true,
    },
    currentTab(newValue, oldValue) {
      if (newValue != oldValue) {
        this.init();
      }
    },
  },
  methods: {
    showDatePicker() {
      this.$refs.calendar.open();
    },
    confirmDate(e) {
      console.log(e);
      this.query.startDate = e.range.before;
      this.query.endDate = e.range.after;
    },
    applyFilters() {
      // 应用筛选条件
      this.init();
      uni.showToast({
        title: '筛选已应用',
        icon: 'success',
        duration: 1500
      });
    },
    init() {
      this.orders = [];
      this.page = 1;
      this.hasMore = true;
      this.loadMore();
    },
    handleSearch() {
      this.init();
    },
    loadMore() {
      if (this.loading || !this.hasMore) return;
      this.loading = true;
      orderListApi({
        page: this.page,
        pageSize: this.pageSize,
        dataType: this.currentTab,
        ...this.query,
      })
        .then((res) => {
          this.orders = [...this.orders, ...res.list.data];
          console.log(this.orders);
          this.loading = false;
          this.initialLoading = false;
          if (res.list.last_page <= this.page) {
            this.hasMore = false;
          } else {
            this.hasMore = true;
            this.page++;
          }
        })
        .catch(() => {
          this.loading = false;
          this.initialLoading = false;
          uni.showToast({
            title: '加载失败，请重试',
            icon: 'none'
          });
        });
    },
    getTotalQuantity(products) {
      if (!products || products.length === 0) return 0;
      return products.reduce((total, product) => {
        return total + (product.total_num || 0);
      }, 0);
    },
    goPay(orderId) {
      uni.navigateTo({
        url: `/pages/payment/payment?orderId=${orderId}`,
      });
    },
    navigateToDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${orderId}`,
      });
    },
    navigateToShop() {
      uni.switchTab({
        url: "/pages/shapping/shapping",
      });
    },
    cancelOrder(orderId) {
      uni.showModal({
        title: "取消订单",
        content: "确定要取消此订单吗？",
        success: (res) => {
          if (res.confirm) {
            cancelOrderApi({
              order_id: orderId,
            }).then((res) => {
              this.init();
            });
          }
        },
      });
    },
    confirmReceived(orderId) {
      uni.showModal({
        title: "确认收货",
        content: "确认已收到商品吗？",
        success: (res) => {
          if (res.confirm) {
            cconfirmOrderApi({
              order_id: orderId,
            }).then((res) => {
              this.init();
            });
          }
        },
      });
    },
    writeReview(orderId) {
      uni.navigateTo({
        url: `/pages/review/write?orderId=${orderId}`,
      });
    },
    rebuyOrder(order) {
      // 显示加载提示
      uni.showLoading({
        title: "正在处理...",
        mask: true
      });
      
      // 创建购物车数据
      if (order.product && order.product.length > 0) {
		  order.product.forEach((item)=>{
			  addCartApi({
			    product_id: item.product_id,
			    total_num: item.total_num,
			    spec_sku_id: item.spec_sku_id
			  }).then((res) => {
			    uni.hideLoading();
			    // 成功提示
			    uni.showModal({
			      title: "已添加到购物车",
			      content: `共${order.product.length}件商品已添加到购物车，是否立即查看？`,
			      confirmText: "去购物车",
			      cancelText: "继续浏览",
			      success: (res) => {
			        if (res.confirm) {
			          uni.navigateTo({
			            url: "/pages/shapping/cart"
			          });
			        }
			      }
			    });
			  }).catch((err) => {
			    uni.hideLoading();
			    // 成功提示
			    uni.showToast({
			      title: err,
			      icon: 'none'
			    });
			  })
		  })
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "商品信息不存在",
          icon: "none"
        });
      }
    },
    // 获取订单来源文字描述
    getOrderSource(sourceCode) {
      const sourceMap = {
        '10': '普通订单',
        '20': '功德分兑换',
        '30': '拼团',
        '40': '砍价',
        '50': '秒杀',
        '60': '礼包购'
      };
      return sourceMap[sourceCode] || '其他';
    },
  },
};
</script>

<style lang="scss">
.order-management {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .page-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #4a3f2b;
    }

    .search-box {
      position: relative;
      flex: 1;
      input {
        height: 64rpx;
        background: #ffffff;
        border-radius: 32rpx;
        padding: 0 60rpx 0 20rpx;
        font-size: 26rpx;
        color: #4a3f2b;
      }

      .search-icon {
        position: absolute;
        right: 20rpx;
        top: 50%;
        transform: translateY(-50%);
        color: #a29171;
      }
    }
  }

  .order-tabs {
    display: flex;
    margin-bottom: 30rpx;
    background: #ffffff;
    border-radius: 10rpx;
    padding: 10rpx;

    .tab {
      flex: 1;
      text-align: center;
      padding: 16rpx 10rpx;
      color: #978868;
      position: relative;
      font-size: 24rpx;

      .tab-inner {
        position: relative;
        display: inline-block;
      }

      .badge {
        position: absolute;
        top: -16rpx;
        right: -16rpx;
        min-width: 32rpx;
        height: 32rpx;
        line-height: 32rpx;
        border-radius: 16rpx;
        background: #e95f3b;
        color: #ffffff;
        font-size: 22rpx;
        text-align: center;
        padding: 0 6rpx;
      }

      &.active {
        color: #4a3f2b;
        font-weight: bold;

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 6rpx;
          background: #978868;
          border-radius: 3rpx;
        }
      }
    }
  }

  .filter-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    padding: 16rpx;
    background: #ffffff;
    border-radius: 10rpx;

    .date-filter {
      display: flex;
      align-items: center;
      flex: 1;
      
      .date-input {
        font-size: 24rpx;
        text-align: center;
        width: 160rpx;
        height: 50rpx;
        padding: 0 6rpx;
      }
      
      .filter-label {
        font-size: 24rpx;
        color: #4a3f2b;
        margin-right: 6rpx;
        white-space: nowrap;
      }

      .date-picker {
        width: 180rpx;
        height: 60rpx;
        background: #f5f3f0;
        border-radius: 6rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .picker-value {
          font-size: 24rpx;
          color: #4a3f2b;
          text-align: center;
        }
      }

      .date-separator {
        margin: 0 10rpx;
        color: #978868;
      }
    }

    .filter-btn {
      width: 90rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #a29171;
      color: #ffffff;
      font-size: 24rpx;
      border-radius: 25rpx;
      padding: 0;
      margin-left: 12rpx;
    }
  }

  .order-list {
    margin-bottom: 30rpx;
  }

  .order-item {
    margin-bottom: 30rpx;
    background: #ffffff;
    border-radius: 10rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);

    .order-header {
      display: flex;
      justify-content: space-between;
      padding: 20rpx;
      border-bottom: 1rpx solid #f5f3f0;
      
      .header-left {
        display: flex;
        flex-direction: column;
      }

      .order-no {
        font-size: 28rpx;
        color: #4a3f2b;
        margin-bottom: 8rpx;
      }

      .order-source {
      // 文字居中
    
       text-align: center;
        font-size: 24rpx;
        padding: 4rpx 4rpx;
        border-radius: 20rpx;
      
        
        &.source-10 {
          color: #a29171;
          background: rgba(162, 145, 113, 0.1);
        }
        
        &.source-20 {
          color: #4caf50;
          background: rgba(76, 175, 80, 0.1);
        }
        
        &.source-30 {
          color: #ff9800;
          background: rgba(255, 152, 0, 0.1);
        }
        
        &.source-40 {
          color: #e91e63;
          background: rgba(233, 30, 99, 0.1);
        }
        
        &.source-50 {
          color: #f44336;
          background: rgba(244, 67, 54, 0.1);
        }
        
        &.source-60 {
          color: #9c27b0;
          background: rgba(156, 39, 176, 0.1);
        }
      }

      .order-status {
        font-size: 28rpx;
        font-weight: bold;
        align-self: center;

        &.status-payment {
          color: #ff9800;
        }

        &.status-delivery {
          color: #FF9800;
        }
        
        &.status-received {
          color: #2196f3;
        }

        &.status-comment {
          color: #4caf50;
        }

        &.status-cancelled {
          color: #9e9e9e;
        }
        
        &.status-all {
          color: #4a3f2b;
        }
      }
    }

    .order-products {
      padding: 20rpx;

      .product-item {
        display: flex;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .product-image {
          width: 140rpx;
          height: 140rpx;
          border-radius: 6rpx;
          background-color: #f5f3f0;
        }

        .product-info {
          flex: 1;
          margin-left: 20rpx;

          .product-name {
            font-size: 28rpx;
            color: #4a3f2b;
            margin-bottom: 10rpx;
          }

          .product-spec {
            font-size: 24rpx;
            color: #a29171;
            margin-bottom: 30rpx;
          }

          .product-price-qty {
            display: flex;
            justify-content: space-between;

            .product-price {
              font-size: 28rpx;
              color: #e95f3b;
              font-weight: bold;
            }

            .product-qty {
              font-size: 26rpx;
              color: #978868;
            }
          }
        }
      }
    }

    .order-footer {
      padding: 20rpx;
      border-top: 1rpx solid #f5f3f0;

      .order-time {
        font-size: 24rpx;
        color: #978868;
        margin-bottom: 10rpx;
      }

      .order-amount {
        font-size: 26rpx;
        color: #4a3f2b;
        text-align: right;
        margin-bottom: 20rpx;

        .amount-total {
          margin-left: 10rpx;
          font-size: 28rpx;
          font-weight: bold;
        }
      }

      .order-actions {
        display: flex;
        justify-content: flex-end;

        .action-btn {
          height: 60rpx;
          line-height: 60rpx;
          padding: 0 30rpx;
          font-size: 26rpx;
          border-radius: 30rpx;
          margin-left: 20rpx;

          &.cancel-btn {
            color: #978868;
            background: #f5f3f0;
            border: 1rpx solid #dcd6cc;
          }

          &.primary-btn {
            color: #ffffff;
            background: #a29171;
          }

          &.review-btn {
            color: #ffffff;
            background: #e95f3b;
          }

          &.detail-btn {
            color: #978868;
            background: #ffffff;
            border: 1rpx solid #dcd6cc;
          }
        }
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #978868;
      margin-bottom: 30rpx;
    }

    .shop-now-btn {
      width: 240rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #a29171;
      color: #ffffff;
      font-size: 28rpx;
      border-radius: 40rpx;
    }
  }

  .load-more {
    padding: 30rpx 0;
    text-align: center;
    color: #978868;
    font-size: 26rpx;

    .loading-spinner {
      display: flex;
      align-items: center;
      justify-content: center;

      .loading-image {
        width: 40rpx;
        height: 40rpx;
        margin-right: 10rpx;
      }
    }
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40rpx;
    margin-top: 80rpx;
  }

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f2f2f2;
    border-top: 6rpx solid #1989fa;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    font-size: 28rpx;
    color: #999;
    margin-top: 20rpx;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
}
</style>
